package com.sunda.spmsweb.ordercontroller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmscommon.feign.IFeignServiceCommon;
import com.sunda.spmscommon.service.ISysLogMqService;
import com.sunda.spmsorder.entity.OrderWerks;
import com.sunda.spmsorder.service.IOrderLogService;
import com.sunda.spmsorder.service.IOrderWerksService;
import com.sunda.spmsuser.entity.SpmsUser;
import com.sunda.spmsuser.service.ISpmsUserService;
import com.sunda.spmsweb.ibmmqservice.SendMessageInterface;
import com.sunda.spmsweb.oaservice.OaService;
import com.sunda.spmsweb.util.JWTUtil;
import feign.FeignException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;

import static com.sunda.spmscommon.Constans.*;
import static com.sunda.spmscommon.Constans.REQUEST_SEND_SRM_ERROR;

/**
 * <p>
 * 工厂请购单 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2021-02-05
 */
@Slf4j
@RestController
@RequestMapping("/orderWerks")
@Api(tags = "工厂请购单接口", description = "工厂请购单接口")
public class OrderWerksController {

    @Autowired
    IOrderWerksService iOrderWerksService;

    @Autowired
    IOrderLogService iOrderLogService;

    @Autowired
    ISpmsUserService iSpmsUserService;

    @Autowired
    SendMessageInterface sendMessageInterface;

    @Autowired
    IFeignServiceCommon iFeignServiceCommon;

    @Autowired
    ISysLogMqService iSysLogMqService;

    @Value("${oa.workflow.id0703}")
    String workflow0703;

    @Value("${oa.workflow.id1201}")
    String workflow1201;

    @Value("${oa.workflow.id3601}")
    String workflow3601;

//    @RequestMapping("/getConfigValue")
//    @ApiOperation(value = "获取Config Value", notes = "获取Config Value", httpMethod = "GET")
//    public ResponseResult getConfigValue() {
//        try {
//            return ResponseResult.success().add("workflow0703", workflow0703)
//                    .add("workflow1201", workflow1201).add("workflow3601", workflow3601);
//        } catch (Exception e) {
//            return ResponseResult.error("请求异常请重试:" + e);
//        }
//    }

    @RequestMapping("/getOrderWerksByWerks")
    @ApiOperation(value = "获取工厂请购单信息（表头 分页）", notes = "获取指定条件下工厂请购单分页信息", httpMethod = "POST")
    public ResponseResult getOrderWerksByWerks(@RequestParam(defaultValue = "1") int pageNo,
                                               @RequestParam(defaultValue = "20") int pageSize,
                                               @RequestParam(required = false) String werks,
                                               @RequestParam(required = false) String status,
                                               @RequestParam(required = false) String spmsId,
                                               @RequestParam(required = false) String urgencyDegree,
                                               @RequestParam(required = false) String dateRequiredStart,
                                               @RequestParam(required = false) String dateRequiredEnd,
                                               @RequestParam(required = false) String applicationDateStart,
                                               @RequestParam(required = false) String applicationDateEnd) {
        Page<OrderWerks> page = new Page<>(pageNo, pageSize);
        try {
            return ResponseResult.success().add("orderWerksList", iOrderWerksService.getOrderWerksByWerks(page, werks, status, spmsId, urgencyDegree, dateRequiredStart, dateRequiredEnd, applicationDateStart, applicationDateEnd));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getOrderWerksDtl")
    @ApiOperation(value = "获取工厂请购单信息（行项目 分页）", notes = "获取工厂请购单信息（行项目）\n" +
            "必输工厂请购单号，示例spmsId:GH01-2020-0002", httpMethod = "POST")
    public ResponseResult getOrderWerksDtl(@RequestParam(defaultValue = "1") int pageNo,
                                           @RequestParam(defaultValue = "20") int pageSize,
                                           String spmsId) {
        try {
            return ResponseResult.success().add("orderWerksDtlList", iOrderWerksService.getOrderWerksDtl(pageNo, pageSize, spmsId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getOrderWerksDtl2")
    @ApiOperation(value = "获取工厂请购单信息（行项目 不分页）", notes = "获取工厂请购单信息（行项目 不分页）\n" +
            "必输工厂请购单号，示例spmsId:GH01-2021-0004，包含日志信息", httpMethod = "POST")
    public ResponseResult getOrderWerksDtl2(String spmsId) {
        try {
            return ResponseResult.success().add("orderWerksDtlList", iOrderWerksService.getOrderWerksDtl2(spmsId)).add("orderLogList", iOrderLogService.orderLogLists(spmsId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getOrderWerksDtlWithInventory")
    @ApiOperation(value = "获取工厂请购单信息(含在库、在途、安全库存)", notes = "获取工厂请购单信息(含在库、在途、安全库存)\n" +
            "必输工厂请购单号，示例 spmsId: GF31-2021-001, GF31-2021-002, GF31-2021-004, GF31-2021-005，包含日志信息", httpMethod = "POST")
    public ResponseResult getOrderWerksDtlWithInventory(String spmsId) {
        try {
            return ResponseResult.success().add("orderWerksDtlList", iOrderWerksService.getOrderWerksDtlWithInventory(spmsId)).add("orderLogList", iOrderLogService.orderLogLists(spmsId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }


    @RequestMapping("/addOrderWerks")
    @ApiOperation(value = "新建工厂请购单及详情", notes = "新建工厂请购单及详情\n" +
            "工厂请购单号生成规则：工厂编号 - werks + 申请日期年份 - applicationDate 截取 + 四位累加序列号；如：GH01-2021-0001\n" +
            "创建工厂请购单涉及操作逻辑：\n1.生成工厂请购单表头；\n2.生成工厂请购单行项目；\n3.更新对应车间请购单状态；" +
            "\n4.增加操作日志；\n5.如果工厂请购单 status = 1，则不提交OA；如果 status = 2，则在1，2，3，4步骤执行完成后继续：\n5.1根据 uuid " +
            "查询到该工厂请购单单据号；\n5.2根据工号查询到用户个人信息；\n5.3提交OA得到reqid；\n5.4成功将reqid更新到工厂请购单里，失败则更新对应工" +
            "厂请购单状态为-提交OA失败；\n5.5记录日志提交成功或失败信息到工厂请购单下；\n" +
            "{\n" +
            "\t\"orderWerks\": {\n" +
            "\t\t\"spmsId\": \"\",\n" +
            "\t\t\"uuid\": \"\",\n" +
            "\t\t\"urgency\": \"0\",\n" +
            "\t\t\"applicationDate\": \"2021-03-08\",\n" +
            "\t\t\"dateRequired\": \"2021-07-01\",\n" +
            "\t\t\"subject\": \"GH01-20210308-郭伟-工厂请购单\",\n" +
            "\t\t\"status\": \"2\",\n" +
            "\t\t\"userId\": \"999950\",\n" +
            "\t\t\"lastName\": \"郭伟\",\n" +
            "\t\t\"werks\": \"GH01\",\n" +
            "\t\t\"workshopCode\": \"\",\n" +
            "\t\t\"deptId\": \"\",\n" +
            "\t\t\"positionId\": \"\",\n" +
            "\t\t\"company\": \"\",\n" +
            "\t\t\"branchPoint\": \"\",\n" +
            "\t\t\"branchLine\": \"\",\n" +
            "\t\t\"purchaseLocation\": \"0\",\n" +
            "\t\t\"justification\": \"请购原因123\",\n" +
            "\t\t\"projectCode\": \"123\",\n" +
            "\t\t\"estimateCost\": 100000,\n" +
            "\t\t\"projectType\": \"1\",\n" +
            "\t\t\"projectStatus\": \"1\",\n" +
            "\t\t\"projectCategory\": \"1\",\n" +
            "\t\t\"shippingType\": \"0\",\n" +
            "\t\t\"shippingFangshi\": \"\",\n" +
            "\t\t\"applicationType\": \"\",\n" +
            "\t\t\"deviceCategory\": \"\",\n" +
            "\t\t\"deviceType\": \"\",\n" +
            "\t\t\"materialCategory\": \"\",\n" +
            "\t\t\"approvalComments\": \"\",\n" +
            "\t\t\"oaId\": \"\",\n" +
            "\t\t\"oaProcessId\": \"0703\",\n" +
            "\t\t\"oaApprovalDate\": \"\",\n" +
            "\t\t\"fieldForOa\": \"\",\n" +
            "\t\t\"detailExplain\": \"\",\n" +
            "\t\t\"relevantProcess\": \"\",\n" +
            "\t\t\"relevantDocument\": \"\",\n" +
            "\t\t\"purchaseManager\": \"\",\n" +
            "\t\t\"costDeptId\": \"\",\n" +
            "\t\t\"costDeptName\": \"\",\n" +
            "\t\t\"deviceStatement\": \"\",\n" +
            "\t\t\"deviceAttachment\": \"\",\n" +
            "\t\t\"comments\": \"\",\n" +
            "\t\t\"oaBianhao\": \"\",\n" +
            "\t\t\"relevantDepartment\": \"\",\n" +
            "\t\t\"attachmentList\": \"\"\n" +
            "\t},\n" +
            "\t\"orderWerksDtlList\": [{\n" +
            "\t\t\t\"spmsId\": \"\",\n" +
            "\t\t\t\"spmsWsId\": \"GH011002-20210308-0002\",\n" +
            "\t\t\t\"rowIdWerks\": 10,\n" +
            "\t\t\t\"rowIdWs\": 10,\n" +
            "\t\t\t\"uuid\": \"\",\n" +
            "\t\t\t\"orderWorkshopUuid\": \"41f9d658ad384b53a2bd9f5daa276405\"\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"spmsId\": \"\",\n" +
            "\t\t\t\"spmsWsId\": \"GH011002-20210308-0002\",\n" +
            "\t\t\t\"rowIdWerks\": 20,\n" +
            "\t\t\t\"rowIdWs\": 20,\n" +
            "\t\t\t\"uuid\": \"\",\n" +
            "\t\t\t\"orderWorkshopUuid\": \"41f9d658ad384b53a2bd9f5daa276405\"\n" +
            "\t\t}\n" +
            "\t]\n" +
            "}" +
            "", httpMethod = "POST")
    @Transactional(rollbackFor = Exception.class)
    public synchronized ResponseResult addOrderWerks(@RequestBody JSONObject jsonObject) {
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
            /** 合单审批创建即提交OA。状态为 2 时才需要提交 OA */
            if (jsonObject.containsKey("orderWerks") && jsonObject.getJSONObject("orderWerks").containsKey("status")) {
                String newStatus = jsonObject.getJSONObject("orderWerks").getString("status");
                /** 0关闭；1机电保存；2机电提交OA成功；3OA审批通过；4OA审批不通过；5提交SRM；6机电提交OA失败；7重新提交OA；8提交SRM失败； */
                if ("2".equals(newStatus)) {
                    /** 工厂请购单及详情成功创建完成之后才提交OA */
                    if (iOrderWerksService.addOrderWerks(jsonObject, uuid)) {
                        String spmsId = iOrderWerksService.getSpmsIdByUuid(uuid);
                        String userId = jsonObject.getJSONObject("orderWerks").getString("userId");
                        SpmsUser spmsUser = iSpmsUserService.getByUserId(userId);
                        OaService oaService = new OaService();
                        int reqid = oaService.createRequest(jsonObject, spmsId, spmsUser, workflow0703, workflow1201, workflow3601);
                        //int reqid = 100000;
                        if (reqid <= 0) {
                            /** 根据uuid将工厂请购单状态修改为-提交OA失败 6 */
                            iOrderWerksService.updateOrderWerksStatusByUuid(uuid, "6");
                            /** 记录工厂请购单提交OA失败日志信息 */
                            iOrderLogService.saveOrderLog(spmsUser.getUserId(),  SUBMIT_OA_ERROR + " " + reqid, uuid);
                            return ResponseResult.success("工厂请购单创建成功，提交OA失败").add("reqid", reqid);
                        }
                        /** 将OA返回的编号信息，写入对应工厂请购单号下，唯一标志：uuid */
                        iOrderWerksService.updateOrderWerksByUuid(uuid, String.valueOf(reqid));
                        /** 记录工厂请购单提交OA成功日志信息 */
                        iOrderLogService.saveOrderLog(spmsUser.getUserId(),  SUBMIT_OA_SUCCESS, uuid);
                        return ResponseResult.success("工厂请购单创建成功，提交OA成功").add("reqid", reqid);
                    }
                    /** 工厂请购单及详情创建失败，返回错误信息 */
                    return ResponseResult.error("工厂请购单创建失败");
                } else {
                    /** 其他状态执行保存即可，车间请购单表头状态不为 2 的也会保存失败 */
                    if(iOrderWerksService.addOrderWerks(jsonObject, uuid)){
                        return ResponseResult.success("工厂请购单创建成功");
                    }
                    return ResponseResult.error("工厂请购单创建失败");
                }
            } else {
                return ResponseResult.error("请求参数错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/updateOrderWerks")
    @ApiOperation(value = "更新工厂请购单表头", notes = "更新工厂请购单表头，工厂请购单号、uuid、申请日期、申请工厂、OA相关字段等不可更新\n" +
            "{\n" +
            "          \"spmsId\": \"GH01-2021-0004\",\n" +
            "          \"uuid\": \"4105e93ae4ca4105af571d13b94c7a2e\",\n" +
            "          \"urgency\": \"0\",\n" +
            "          \"applicationDate\": \"2021-02-24\",\n" +
            "          \"dateRequired\": \"2021-05-25\",\n" +
            "          \"subject\": \"GH01 - 20001 -2021-02-24\",\n" +
            "          \"status\": \"1\",\n" +
            "          \"userId\": \"20001\",\n" +
            "          \"lastName\": \"20001\",\n" +
            "          \"werks\": \"GH01\",\n" +
            "          \"workshopCode\": \"20001\",\n" +
            "          \"deptId\": \"123\",\n" +
            "          \"positionId\": \"11\",\n" +
            "          \"company\": \"company\",\n" +
            "          \"branchPoint\": \"12345\",\n" +
            "          \"branchLine\": \"123456\",\n" +
            "          \"purchaseLocation\": null,\n" +
            "          \"justification\": null,\n" +
            "          \"projectCode\": null,\n" +
            "          \"estimateCost\": 0,\n" +
            "          \"projectType\": null,\n" +
            "          \"projectStatus\": null,\n" +
            "          \"projectCategory\": null,\n" +
            "          \"shippingType\": null,\n" +
            "          \"shippingFangshi\": null,\n" +
            "          \"applicationType\": null,\n" +
            "          \"deviceCategory\": null,\n" +
            "          \"deviceType\": null,\n" +
            "          \"materialCategory\": null,\n" +
            "          \"approvalComments\": null,\n" +
            "          \"oaId\": \"20001\",\n" +
            "          \"oaProcessId\": null,\n" +
            "          \"oaApprovalDate\": null,\n" +
            "          \"fieldForOa\": null,\n" +
            "          \"detailExplain\": null,\n" +
            "          \"relevantProcess\": null,\n" +
            "          \"relevantDocument\": null,\n" +
            "          \"purchaseManager\": null,\n" +
            "          \"costDeptId\": null,\n" +
            "          \"costDeptName\": null,\n" +
            "          \"deviceStatement\": null,\n" +
            "          \"deviceAttachment\": null,\n" +
            "          \"comments\": null,\n" +
            "          \"oaBianhao\": null,\n" +
            "          \"relevantDepartment\": null,\n" +
            "          \"attachmentList\": null,\n" +
            "          \"createTime\": \"2021-02-24 01:48:35\"\n" +
            "        }\n" +
            "", httpMethod = "POST")
    public synchronized ResponseResult updateOrderWerks(@RequestBody JSONObject jsonObject) {
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        OrderWerks orderWerks = iOrderWerksService.getByUuid(jsonObject.getString("uuid"));
        if (orderWerks == null){
            return ResponseResult.error("请求工厂请购单不存在请刷新重试");
        }
        if ("2".equals(orderWerks.getStatus()) && StringUtils.isNotEmpty(orderWerks.getOaBianhao())){
            return ResponseResult.error("工厂请购单已更新请刷新重试");
        }
        JSONObject doc = new JSONObject();
        doc.put("orderWerks", jsonObject);
        try {
            int resp = iOrderWerksService.updateOrderWerks(jsonObject, userId);
            String spmsId = jsonObject.getString("spmsId");
            String uuid = jsonObject.getString("uuid");
            if (resp > 0){
                String status = jsonObject.getString("status");
                /** status = 2 则提交OA，只要oaBianhao字段不为空则为重新提交OA； status = 7 驳回重新提交 OA；*/
                if ("2".equals(status)){
                    if (StringUtils.isEmpty(jsonObject.getString("oaBianhao"))){
                        SpmsUser spmsUser = iSpmsUserService.getByUserId(userId);
                        OaService oaService = new OaService();
                        int reqid = oaService.createRequest(doc, spmsId, spmsUser, workflow0703, workflow1201, workflow3601);
                        if (reqid <= 0) {
                            /** 根据uuid将工厂请购单状态修改为-提交OA失败 6 */
                            iOrderWerksService.updateOrderWerksStatusByUuid(uuid, "6");
                            /** 记录工厂请购单提交OA失败日志信息 */
                            iOrderLogService.saveOrderLog(userId,  SUBMIT_OA_ERROR + " " + reqid, uuid);
                            return ResponseResult.success("工厂请购单创建成功，提交OA失败").add("reqid", reqid);
                        }
                        /** 将OA返回的编号信息，写入对应工厂请购单号下，唯一标志：uuid */
                        iOrderWerksService.updateOrderWerksByUuid(uuid, String.valueOf(reqid));
                        /** 记录工厂请购单提交OA成功日志信息 */
                        iOrderLogService.saveOrderLog(userId,  SUBMIT_OA_SUCCESS, uuid);
                        return ResponseResult.success("工厂请购单创建成功，提交OA成功").add("reqid", reqid);
                    } else {
                        SpmsUser spmsUser = iSpmsUserService.getByUserId(userId);
                        OaService oaService = new OaService();
                        if (!oaService.reSubmitOa(doc, spmsUser, workflow0703, workflow1201, workflow3601)){
                            /** 重新提交OA 失败，则修改单据状态为-提交OA失败 6  */
                            iOrderWerksService.updateOrderWerksStatusByUuid(uuid, "6");
                            /** 记录工厂请购单提交OA失败日志信息 */
                            iOrderLogService.saveOrderLog(userId,  SUBMIT_OA_ERROR, uuid);
                            return ResponseResult.success("工厂请购单重新提交OA失败");
                        }
                        /** 重新提交OA成功，则更新状态为 2 - 机电提交OA成功 */
                        iOrderWerksService.updateOrderWerksStatusByUuid(uuid, "2");
                        /** 记录工厂请购单提交OA成功日志信息 */
                        iOrderLogService.saveOrderLog(userId,  SUBMIT_OA_SUCCESS, uuid);
                        return ResponseResult.success("工厂请购单创建成功，提交OA成功");
                    }
                }
                if ("7".equals(status)){
                    if (StringUtils.isEmpty(jsonObject.getString("oaBianhao")) || StringUtils.isEmpty(jsonObject.getString("oaProcessId"))){
                        return ResponseResult.error("重新提交，OA编号不能为空");
                    }
                    SpmsUser spmsUser = iSpmsUserService.getByUserId(userId);
                    OaService oaService = new OaService();
                    if (!oaService.reSubmitOa(doc, spmsUser, workflow0703, workflow1201, workflow3601)){
                        /** 重新提交OA 失败，则修改单据状态为-提交OA失败 6  */
                        iOrderWerksService.updateOrderWerksStatusByUuid(uuid, "6");
                        /** 记录工厂请购单提交OA失败日志信息 */
                        iOrderLogService.saveOrderLog(userId,  SUBMIT_OA_ERROR, uuid);
                        return ResponseResult.success("工厂请购单创建成功，提交OA失败");
                    }
                    /** 重新提交OA成功，则更新状态为 2 - 机电提交OA成功 */
                    iOrderWerksService.updateOrderWerksStatusByUuid(uuid, "2");
                    /** 记录工厂请购单提交OA成功日志信息 */
                    iOrderLogService.saveOrderLog(userId,  SUBMIT_OA_SUCCESS, uuid);
                    return ResponseResult.success("工厂请购单创建成功，提交OA成功");
                }
                return ResponseResult.success();
            }
            return ResponseResult.error();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getOrderWerksDtlById")
    @ApiOperation(value = "获取指定工厂请购单表头、行、日志-OA页面", notes = "获取指定工厂请购单表头、行、日志，" +
            "必输工厂请购单号，示例spmsId:GH01-2021-0004，包含日志信息。请求示例url：\n" +
            "http://192.168.106.90/external/#/external/oaview?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTc5MzQ0ODEsInVzZXJJZCI6Ijk5OTk0NyJ9.DcXsnU41dfKKbXWx15ZreieNy6hFhqyaR2ezsUuP_Bc&spmsId=GF03-2021-003", httpMethod = "POST")
    public ResponseResult getOrderWerksDtlById(String spmsId) {
        try {
            return ResponseResult.success().add("orderWerksDtlList", iOrderWerksService.getOrderWerksDtlById(spmsId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getOrderWerksOALog")
    @ApiOperation(value = "获取工厂请购单OA日志", notes = "获取工厂请购单在OA日志信息，实时向OA发一个请求，示例 requestId = 838295, 933533", httpMethod = "POST")
    public ResponseResult getOrderWerksOALog(String requestId) {
        try {
            OaService oaService = new OaService();
            return ResponseResult.success().add("orderWerksOALog", oaService.getOALog(requestId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/updateOrderWerksStatus")
    @ApiOperation(value = "工厂请购单OA审批通过", notes = "OA 审批通过工厂请购单，oaBianhao：工厂请购单在 OA 编号；oaStatus：S - OA审批通通过；其他状态被认为驳回；\n" +
            "示例参数：oaBianhao = 938287, oaStatus = S ", httpMethod = "POST")
    public ResponseResult updateOrderWerksStatus(String oaBianhao, String oaStatus) {
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            int result = iOrderWerksService.updateOrderWerksStatus(userId, oaBianhao, oaStatus);
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

//    @RequestMapping("/orderWerksToSrm")
//    @ApiOperation(value = "工厂请购单OA审批通过提交SRM", notes = "根据工厂请购单uuid查询OA审批通过请购单，" +
//            "提交SRM - 示例uuid = ed64f63d663141028cad97a42510da89", httpMethod = "POST")
//    public ResponseResult orderWerksToSrm(String uuid) {
//        try {
//            //Map<String, Object> map = iOrderWerksService.orderWerksToSrm(uuid);
//            return sendMessageInterface.spms_srm_purchase_info(uuid);
//        } catch (Exception e) {
//            return null;
//        }
//    }

    @RequestMapping("/resubmitSrm")
    @ApiOperation(value = "工厂请购单OA审批通过提交SRM失败重提", notes = "工厂请购单OA审批通过提交SRM失败重提\n" +
            "OA审批通过的工厂请购单，后端默认自动提交SRM 3->5, 3审批通过是过程状态，提交成功则状态为 5-提交SRM；" +
            "提交失败则状态更新为 8-提交SRM失败；存在部分数据为状态 3-OA 审批通过，也允许重提SRM；" +
            "对于此类提交SRM失败-状态8的数据做重新提交SRM操作。\n" +
            "示例参数：oaBianhao =  ", httpMethod = "POST")
    public ResponseResult resubmitSrm(String oaBianhao) {
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            OrderWerks orderWerks = iOrderWerksService.getByOaBianhao(oaBianhao);
            if (orderWerks == null){
                return ResponseResult.error("数据查询错误");
            }
            if (!"3".equals(orderWerks.getStatus()) && !"8".equals(orderWerks.getStatus())){
                return ResponseResult.error("当前状态不允许操作").add("orderWerks", orderWerks);
            }
            /** 对于 OA 审批通过重提SRM的单据，发送消息给 SRM 系统；
             * 20211101 由MQ方式修改为REST请求方式
             * */
            JSONObject restDataToSrm = restDataToSrm(oaBianhao);
            log.info("=======restDataToSrm=======" + restDataToSrm);
            JSONObject message = JSONObject.parseObject(iFeignServiceCommon.sendRestToSapCommon(restDataToSrm));
            log.info("=======message=======" + message);
            JSONObject RETURN_DATA = message.getJSONObject("RESPONSE").getJSONObject("RETURN_DATA");
            if (RETURN_DATA.containsKey("status") && "S".equals(RETURN_DATA.getString("status"))){
                /** 状态 5 表示提交 SRM **/
                String status = String.valueOf(5);
                iOrderWerksService.updateOrderWerksStatusByOaBianhao(userId, oaBianhao, status);
                iSysLogMqService.addSysLogMq("3", "spms_srm_purchase_info", REQUEST_SEND_SRM,
                        "spms_srm_purchase_info", restDataToSrm.toJSONString(), message.toJSONString(), oaBianhao);
                return ResponseResult.success("OA审批通过，提交SRM成功")
                        .add("orderWerks", iOrderWerksService.getByOaBianhao(oaBianhao));
            } else {
                String status = String.valueOf(8);
                iOrderWerksService.updateOrderWerksStatusByOaBianhao(userId, oaBianhao, status);
                iSysLogMqService.addSysLogMq("3", "spms_srm_purchase_info", REQUEST_SEND_SRM_ERROR,
                        "spms_srm_purchase_info", restDataToSrm.toJSONString(), message.toJSONString(), oaBianhao);
                return ResponseResult.error("OA审批通过，提交SRM出错")
                        .add("message", message.toJSONString())
                        .add("dataToSap", restDataToSrm.toJSONString());
            }

            /** 原MQ请求方式；状态 5 表示提交 SRM 成功；状态 8 表示提交 SRM 失败；*/
//            int resp = sendMessageInterface.spms_srm_purchase_info2(oaBianhao);
//            if (resp == 1){
//                String status = String.valueOf(5);
//                iOrderWerksService.updateOrderWerksStatusByOaBianhao(userId, oaBianhao, status);
//                return ResponseResult.success("OA审批通过，提交SRM成功");
//            }
//            if (resp == 0){
//                String status = String.valueOf(8);
//                iOrderWerksService.updateOrderWerksStatusByOaBianhao(userId, oaBianhao, status);
//                return ResponseResult.error("OA审批通过，提交SRM出错");
//            }
//            return ResponseResult.success();
        } catch (FeignException feignException){
            feignException.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求SRM失败 FeignException").add("error", feignException.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    JSONObject restDataToSrm(String oaBianhao){
        JSONObject doc = new JSONObject();
        Map<String, Object> DATA = iOrderWerksService.orderWerksToSrm2(oaBianhao);
        JSONObject REQUEST = new JSONObject();
        JSONObject ESB_ATTRS = new JSONObject();
        JSONObject REQUEST_DATA = new JSONObject();
        ESB_ATTRS.put("Application_ID", "00020000000004");
        ESB_ATTRS.put("Transaction_ID", UUID.randomUUID().toString());
        ESB_ATTRS.put("App_ID", "SPMS");

        REQUEST_DATA.put("Head", DATA.get("Head"));
        REQUEST_DATA.put("Items", DATA.get("Items"));
        REQUEST_DATA.put("Operation", "spms_srm_purchase_info");
        REQUEST_DATA.put("Type", "purchase_info");

        REQUEST.put("ESB_ATTRS", ESB_ATTRS);
        REQUEST.put("REQUEST_DATA", REQUEST_DATA);

        doc.put("REQUEST", REQUEST);
        return doc;
    }

    @RequestMapping("/getFrequencyMaterialNo")
    @ApiOperation(value = "获取高频SKU报表", notes = "获取高频SKU报表\n" +
            "获取高频SKU报表/以工厂请购单为基准\n" +
            "示例参数：werks = GF03，materialNo = 210022851，beginDate = 2021-07-01，endDate = 2022-01-17；\n" +
            "物料编号可选输入，为空则查所有，其余字段必输，日期参数为工厂请购单创建日期；\n" +
            "\n", httpMethod = "POST")
    public ResponseResult getFrequencyMaterialNo(@RequestParam String werks,
                                                 String materialNo,
                                                 @RequestParam String beginDate,
                                                 @RequestParam String endDate) {
        try {
            if (StringUtils.isEmpty(werks) || StringUtils.isEmpty(beginDate) || StringUtils.isEmpty(endDate)){
                return ResponseResult.error("请求参数错误");
            }
            return ResponseResult.success().add("frequencyMaterialNo", iOrderWerksService.getFrequencyMaterialNo(werks, materialNo, beginDate, endDate));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

}
